import styled from 'styled-components'
import {Form, Input, Modal} from 'antd'
import {useEffect, useRef, useState} from 'react'
import {userInfo as $userInfo, userInfoEdit} from '@/api/user.js'
import useConfigStore from '@/store/useConfigStore.js'
import {getImageDimensions} from '@/utils/utils.js'
import {message} from 'antd';
import Cropper from "cropperjs";
import _ from 'lodash'
import "cropperjs/dist/cropper.css";
import {isBlob} from '@/utils/business.js'
import {useNavigate} from 'react-router-dom'

const Container = styled.div`

    height: 100%;
    background: #F4F4F4;
    width: 100%;
    box-sizing: border-box;
    padding-top: 30px;

    .inner-box {
        height: 100%;
        background: #fff;
        width: 1200px;
        margin: 0 auto;
        box-sizing: border-box;
        padding-top: 50px;

        .title {
            color: #000000;
            font-size: 20px;
            font-weight: 700;
            line-height: 26px;
            text-align: center;
            margin-bottom: 44px;
        }

        .textArea-box {
            height: 200px;
            border-radius: 4px;
            border: 1px solid #DCDFE6;
            display: flex;
            flex-direction: column;
            box-sizing: border-box;
            padding-bottom: 8px;

            .count {
                color: #cbced3;
                font-size: 14px;
                font-weight: 400;
                line-height: 22px;
                letter-spacing: -0.01px;
                text-align: end;
                padding-right: 10px;
            }

            .ant-input {
                flex: 1;
                //height: 149px;
                font-size: 14px;
                border: none !important;
                box-shadow: none !important;
                //background: #F5F9FE !important;
                border-radius: 10px;
                padding: 10px 10px 0px 10px;
            }
        }

        .cover-box {
            width: 80px;
            height: 80px;
            overflow: hidden;

            .cover {
                width: 100%;
                height: 100%;
            }
        }

        .save {
            width: 200px;
            height: 44px;
            border-radius: 35px;
            background: #58B530;
            line-height: 44px;
            color: #ffffff;
            text-align: center;
            font-size: 16px;
            font-weight: 700;
            letter-spacing: 0.48px;
            margin: 0 auto;
            margin-top: 54px;
            cursor: pointer;
        }


    }
`

function MTextArea({self_introduction,...props}) {
  const {TextArea} = Input;
  return (<>
    <div className={'textArea-box'}>
      <TextArea rows={4} maxLength={200} showCount={false} style={{resize: 'none'}} {...props}/>
      <div className={'count'}>{200 - (self_introduction?.length || 0)}</div>
    </div>
  </>)
}

function MUpload({value, onAvatarChange}) {
  const url = isBlob(value) ? URL.createObjectURL(value) : value
  return (<>
    <div className={'cover-box'}>
      <label>
        <img src={url} alt="" className={'cover'}/>
        <input style={{display: 'none'}} type="file" onChange={onAvatarChange}/>
      </label>
    </div>

  </>)
}

function UploadModel({isModalOpen, handleCancel, tmpUrl, realTimePreview = true, onAvatarChange, setAvatar}) {
  const defaultOptions = {
    aspectRatio: 1,
    zoomable: true,
    zoomOnTouch: true,
    zoomOnWheel: true,
    cropBoxMovable: true,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: true,
    autoCrop: true,
    background: true,
    highlight: true,
    center: true,
    responsive: true,
    restore: true,
    checkCrossOrigin: true,
    checkOrientation: true,
    scalable: true,
    modal: true,
    guides: true,
    movable: true,
    rotatable: true,
    dragMode: 'move',
    minCropBoxWidth: 166,
    minCropBoxHeight: 166
  };
  const imgElRef = useRef()
  const previewRef = useRef()
  let cropperRef = useRef()

  function croppered() {
    if (!cropperRef.current) return
    const canvas = cropperRef.current?.getCroppedCanvas({
      width:460,
      height: 460,
      maxWidth: 460,
      maxHeight: 460,
      fillColor: '#000',
    })
    canvas.toBlob(blob => {
      if (!blob) return;
      setAvatar(blob)
    });
  }

  function init() {
    cropperRef.current = new Cropper(imgElRef.current, {
      ...defaultOptions,
      preview: previewRef.current
    });
  }

  useEffect(() => {
    init()
    return () => {
      if (cropperRef.current) {
        cropperRef.current?.destroy();
      }
    }
  }, [tmpUrl])
  return (<>
    <Modal open={isModalOpen} onCancel={handleCancel} centered={true} width={550} closable={false} footer={null}
           wrapClassName="upload-modal">
      <div className={'title'}>上传头像</div>
      <div className={'line'}></div>
      <div className={'cropper-box'}>
        <div className={'left-box'}>
          <div className={'cover-box'}>
            <img src={tmpUrl} alt="" ref={imgElRef}/>
          </div>
          <div className={'operator'}>
            <label>
              <input style={{display: 'none'}} type="file" onChange={onAvatarChange}/>
              <div className={'operator-left'}> 重新上传</div>
            </label>
            <div className={'operator-right'}>
              <i className="iconfont icon-add" onClick={() => {
                cropperRef?.current?.zoom(0.1);
              }}>
              </i>
              <i className="iconfont icon-reduce" onClick={() => {
                cropperRef?.current?.zoom(-0.1);
              }}>
              </i>
              <i className="iconfont icon-refresh" onClick={() => {
                cropperRef?.current?.rotate(90);
              }}>
              </i>
            </div>
          </div>
        </div>
        <div className={'right-box'}>
          <div className={'preview-cover'} ref={previewRef}></div>
          <div className={'tips'}>头像预览</div>
        </div>
      </div>
      <div className={'line'} style={{marginTop: '59px'}}></div>
      <div className={'confirm-box'}>
        <div className={'confirm'} onClick={croppered}>确认</div>
        <div className={'cancel'} onClick={handleCancel}>取消</div>
      </div>

    </Modal>
  </>)
}

export default function editProfilePage() {
  const [form] = Form.useForm();
  const formRef = useRef()
  const navigate = useNavigate()
  const userInfo = useConfigStore(state => state.userInfo)
  const setUserInfo = useConfigStore(state => state.setUserInfo)
  const [tmlUrl, setTmlUrl] = useState('')
  const [isModalOpen, setIsModalOpen] = useState(false)
  const self_introduction = Form.useWatch('self_introduction', form);
  async function getUserInfo() {
    const res = await $userInfo()
    if (res.result.status_info.status_code !== 100) {
      return
    }
    setUserInfo(res.result?.user_info)
    form.setFieldValue(['user_name'], res.result?.user_info?.user_name)
    form.setFieldValue(['self_introduction'], res.result?.user_info?.self_introduction)
    form.setFieldValue(['avatar_file'], res.result?.user_info?.profile_picture)
  }

  async function onAvatarChange(e) {
    const file = e.target.files[0];

    if (file && file.type.startsWith("image/")) {
      const {width, height} = await getImageDimensions(URL.createObjectURL(file));
      if (width < 460 || height < 460) {
        message.open({
          type: 'warning',
          content: '图片尺寸必须大于460x460'
        })
      } else {
        setTmlUrl(URL.createObjectURL(file))
        setIsModalOpen(true)
      }
      e.target.value = null
    }
  }

  function setAvatar(url) {
    form.setFieldValue(['avatar_file'], url)
    setIsModalOpen(false)
  }
 const handleSave = _.debounce(()=>{
   form.validateFields()
       .then(async values => {
         const {user_name,self_introduction,avatar_file} = values
         const res = await userInfoEdit(user_name,self_introduction, avatar_file);
         if(res.result.status_info.status_code!== 100) {
           message.open({
             type: 'error',
             content: res.result.status_info.status_message
           })
           return
         }
         navigate(-1)

       })
 }, 200)

  useEffect(() => {
    getUserInfo()
  }, [])

  return (<>
    <Container>
      <div className={'inner-box'}>
        <div className={'title'}>个人资料</div>
        <Form form={form} ref={formRef} style={{maxWidth: '542px', margin: '0 auto'}} colon={false}>
          <Form.Item name="user_name" validateTrigger="onBlur" labelCol={{style: {width: 80}}} label="用户名称" rules={[
            {required: true, message: '请输入用户名称'}
          ]}>
            <Input/>
          </Form.Item>
          <Form.Item name="self_introduction" validateTrigger="onBlur" labelCol={{style: {width: 80}}} label="基本介绍">
            <MTextArea self_introduction={self_introduction}/>
          </Form.Item>
          <Form.Item name="avatar_file" validateTrigger="onBlur" label="上传头像" labelCol={{style: {width: 80}}}>
            <MUpload onAvatarChange={onAvatarChange}/>
          </Form.Item>
        </Form>
        {isModalOpen &&
            <UploadModel tmpUrl={tmlUrl} isModalOpen={isModalOpen} onAvatarChange={onAvatarChange} setAvatar={setAvatar}
                         handleCancel={() => {
                           setIsModalOpen(false)
                         }}/>}
        <div className={'save'} onClick={handleSave}>保存</div>
      </div>

    </Container></>)
}